package antidestiny.java2dex;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

import com.kodis.listener.FileChangeListener;
import com.kodis.ui.fragment.EditorFragment;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import antidestiny.java2dex.compiler.Compiler;
import antidestiny.java2dex.file.FileConstructor;
import antidestiny.java2dex.ui.activity.AdActivity;
import antidestiny.java2dex.ui.activity.CompileActivity;
import antidestiny.java2dex.ui.activity.OpenSourceActivity;
import antidestiny.java2dex.ui.activity.TerminalActivity;
import antidestiny.java2dex.ui.activity.TestActivity;
import antidestiny.java2dex.ui.activity.WorkActivity;
import antidestiny.utilib.Aide;
import antidestiny.utilib.io.FileUtils;

public class MainActivity extends AppCompatActivity implements Compiler.ICompiler, FileChangeListener ,View.OnLayoutChangeListener{
    final String PREFERENCE_NAME = "MAIN";
    final String PREF_BOOL_FIRSTTIME = "FIRSTTIME";

    final String QUIKJAVA_DIR = "quickJava";
    File quikJavaDir,
            quikJava,
            projDir,
            src,
            outputDir;

    EditorFragment editorFragment;
    View rootView;

    boolean runAfterSave = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Aide.tryDebug(this);
        SharedPreferences preferences = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);
        preferences.edit().putBoolean(PREF_BOOL_FIRSTTIME, false).apply();
        checkRtJar();
        quikJavaDir = getDir(QUIKJAVA_DIR, MODE_PRIVATE);
        projDir = new File(quikJavaDir + "/QuickJava");
        src = new File(quikJavaDir + "/QuickJava/src");
        outputDir = new File(quikJavaDir + "/QuickJava/output");
        quikJava = new File(quikJavaDir + "/QuickJava/src/j2d/quick/test/Main.java");
        rootView=findViewById(R.id.activityRootView);
        if (!quikJava.exists()) {
            if (projDir.exists()) FileUtils.removeDir(projDir, null);
            FileConstructor projectConstruct = new FileConstructor();
            try {
                projectConstruct.createProject("QuickJava", "j2d.quick.test", quikJavaDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!quikJava.exists()) {
            String errorMsg = "文件无法创建，你无法使用即时运行功能。请向开发者回报此问题。";
            Aide.eDialog(this, errorMsg);
            Aide.e(errorMsg);
        } else {
            editorFragment = new EditorFragment();
            editorFragment.setFileChangeListener(this);
            Bundle bundle = new Bundle();
            bundle.putSerializable(EditorFragment.FILE_KEY, quikJava);
            editorFragment.setArguments(bundle);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.quickCodeHolder, editorFragment).commit();
        }

    }

    /**
     * rt.jar是java必须的
     */
    void checkRtJar() {
        File dir = getFilesDir();
        String[] files = dir.list();
        boolean rtExists = false;
        if (files != null)
            for (String file : files) {
                if (file.equals("rt.jar"))
                    rtExists = true;
            }
        if (!rtExists) {
            Aide.t("rt不存在，试着创建");
            try {
                byte[] bytes = FileUtils.read(getAssets().open("rt.jar"));
                FileUtils.write(new File(dir.getAbsolutePath() + "/rt.jar"), bytes);
            } catch (IOException e) {
                e.printStackTrace();
                finish();
            }

        } else {
            Aide.t("rtjar存在，位置是：" + dir);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        rootView.addOnLayoutChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        rootView.removeOnLayoutChangeListener(this);
        if (editorFragment.isChanged())
            editorFragment.save();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonCompile:
                startActivity(new Intent(this, CompileActivity.class));
                break;
            case R.id.buttonRun:
                startActivity(new Intent(this, TerminalActivity.class));
                break;
            case R.id.button_new:
                startActivity(new Intent(this, WorkActivity.class));
                break;
            case R.id.button_test:
                startActivity(new Intent(this, TestActivity.class));
                break;
            case R.id.quickRun:
                if (editorFragment.isChanged()) {
                    runAfterSave = true;
                    editorFragment.save();
                } else
                    run();
                break;

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.donate_menu:
                startActivity(new Intent(this, AdActivity.class));
                break;
            case R.id.opensource:
                startActivity(new Intent(this, OpenSourceActivity.class));
                break;
        }
        return true;
    }

    @Override
    public void onCompileFinish(Bundle msg) {
        //没有错误报告
        if (!msg.getBoolean(Compiler.KEY_ERROR_REPORTED, false)) {
            Intent intent = new Intent(this, TerminalActivity.class);
            intent.putExtra(Jing.DEX_FILE, outputDir + "/quick.jar");
            startActivity(intent);
        }
    }

    @Override
    public void onFileOpen() {

    }

    @Override
    public void onFileChanged(boolean save) {

    }

    @Override
    public void onFileSave() {
        if (runAfterSave) {
            runAfterSave = false;
            run();
        }
    }

    private void run() {
        final Compiler compiler = new Compiler(src, null, outputDir, "quick.jar", this);
        compiler.setListener(this);
        compiler.compile();
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        float height = metric.heightPixels;  // 屏幕高度（像素）
        LinearLayout buttons=(LinearLayout)findViewById(R.id.buttonGroup);
        LinearLayout.LayoutParams params=(LinearLayout.LayoutParams)buttons.getLayoutParams();
        if((bottom-top)/height<0.75&&params.weight!=0){
            params.weight=0;
            buttons.setLayoutParams(params);
        }
        else if(params.weight!=1){
            params.weight=1;
            buttons.setLayoutParams(params);
        }
    }
}
